<template>
  <div class="app-container">
    <div class="flex">
      <el-input
        v-model="listQuery.title"
        :placeholder="t('message.layout.title')"
        style="width: 200px"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-select
        v-model="listQuery.status"
        :placeholder="t('message.layout.importance')"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in importanceOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-select
        v-model="listQuery.author"
        :placeholder="t('message.layout.type')"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in calendarTypeOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-button
        v-waves
        style="margin:0 0 20px 20px;"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        {{ $t('message.layout.search') }}
      </el-button>
      <el-button
        v-waves
        style="margin:0 0 20px 20px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
      地图添加
      </el-button>
       <el-button
      v-waves
			        :loading="downloadLoading"
			        style="margin:0 0 20px 20px;"
			        type="primary"
			        icon="el-icon-document"
			        @click="handleDownload"
			      >
        		  {{ $t('message.layout.excelexport') }}     
      			</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column
        label="单位"
        prop="abstractContent"
        sortable="custom"
        align="center"
        width="180"
        :class-name="getSortClass('abstractContent')"
      >
        <template #default="{row}">
          <span>{{ row.abstractContent }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('message.layout.date')"
        width="180px"
        align="center"
      >
        <template #default="{row}">
          <span>{{ $timeFormat(row.timestamp) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('message.layout.title')"
        min-width="150px"
        align="center"
      >
        <template #default="{row}">
          <span
            class="link-type"
            @click="handleUpdate(row)"
          >{{
            row.title
          }}</span>
          <!-- <el-tag>{{ row.type }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column
        :label="t('message.layout.author')"
        width="180px"
        align="center"
      >
        <template #default="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="showReviewer"
        :label="t('message.layout.reviewer')"
        width="110px"
        align="center"
      >
        <template #default="{row}">
          <span style="color: red">{{ row.reviewer }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('message.layout.importance')"
        width="105px"
        align="center"
      >
        <template #default="{row}">
          <svg-icon
            v-for="n in +row.status"
            :key="n"
            name="star"
            class="iconfont icon-xingji"
          />
        </template>
      </el-table-column>
      
      <el-table-column
        :label="t('message.layout.readings')"
        align="center"
        width="95"
      >
        <template #default="{row}">
          <span
            v-if="row.pageviews"
            class="link-type"
            @click="handleGetPageviews(row.pageviews)"
          >{{ row.pageviews }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      
      <el-table-column
        :label="t('message.layout.status')"
        class-name="status-col"
        width="100"
        align="center"
      >
        <template #default="{row}">
          <el-tag :type="row.status">
            {{ row.fullContent }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('message.layout.actions')"
        align="center"
        width="230"
        class-name="fixed-width"
      >
        <template #default="{row, $index}">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
          >
            {{ t("message.layout.edit") }}
          </el-button>          
          <el-button            
            size="mini"
            @click="handleModifyStatus(row, 'draft')"
          >
            {{ t("message.layout.draft") }}
          </el-button>
          <el-button
            v-if="row.status !== 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            {{ t("message.layout.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :total="total"
      v-show="total > 0"
      v-model:page="listQuery.currentPage"
      v-model:limit="listQuery.pageCount"
      @current-change="handleCurrentChange"
      layout="total,prev, pager, next, jumper"
    />
   <ComplexDialog @updateData="updateData" @createData="createData" ref="dialogPop" v-model="dialogFormVisible" v-model:dialogStatus="dialogStatus"></ComplexDialog>

   
  </div>
</template>

<script lang='ts'>
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  nextTick,
  onMounted,
  unref
} from 'vue'
import { ElForm, ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash'
import {
  getArticles,
  getPageviews,
  createArticle,
  deleteArticle,
  updateArticle,
  defaultArticleModel,
  ArticleType
} from '/@/request/articles'
import { ArticleModel } from '/@/model/articleModel'

//import { exportJson2Excel } from '@/utils/excel'
//import { formatJson } from '@/utils'
import { useI18n } from 'vue-i18n'
//import jjmbmlJson from '/@/mock/jjmbml.json';
// import Pagination from '@/components/Pagination/index.vue'
import '/@/assets/iconfont/iconfont.css'
import { useRouter } from 'vue-router';
import { useStore } from '/@/store/index';
import Assert from '/@/utils/shf/Assert'
import GlobalConfig from '/@/utils/config/GlobalConfig'
import { exportJson2Excel } from '/@/utils/excel'
import { formatJson } from '/@/utils'
import ComplexDialog from './components/ComplexDialog.vue'

export default defineComponent({
  components: {
    // Pagination
    ComplexDialog
  },
  setup() {
     const dialogPop = ref(null);
    let allData:any[] = [];
  	const store=useStore();
    const { t } = useI18n();
   
    const router = useRouter()
    const calendarTypeOptions = ['通信类','能源动力','交通枢纽','军工类','生命线','次生灾害','金融类','工矿化工']

    const calendarTypeKeyValue = calendarTypeOptions.reduce(
      (acc: { [key: string]: string }, cur) => {
        acc[cur.key] = cur.displayName
        return acc
      },
      {}
    ) as { [key: string]: string }
    const dataForm = ref(ElForm)
    const dataMap = reactive({
          dialogFormVisible: false,
      dialogStatus: '',
      authorInp:"",
      tableKey: 0,
      list: Array<ArticleModel>(),
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageCount: 10,
        importance: '经济目标',
        title: undefined,
        type: undefined,
        sort: undefined
      },

      importanceOptions: [1, 2, 3],
      calendarTypeOptions: calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],

      statusOptions: ['良好', '破坏', '损毁'],
      showReviewer: false,
      textMap: {
        update: '编辑',
        create: '添加'
      },

      dialogPageviewsVisible: false,
      pageviewsData: [],
      rules: {
        author: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
       
        title: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ],
        status: [
          { required: true, message: 'area is required', trigger: 'blur' }
        ],
        /*
        pageviews: [
          { required: true, message: 'location is required', trigger: 'change' }
        ],*/
      },
      downloadLoading: false,
      tempArticleModel: defaultArticleModel,
      handleCurrentChange(page?: any) {
        dataMap.listQuery.currentPage = page;
        dataMap.list = allData.slice((dataMap.listQuery.currentPage-1)*dataMap.listQuery.pageCount,(dataMap.listQuery.currentPage)*dataMap.listQuery.pageCount);
      },
      handleSizeChange(val: any) {
        dataMap.getList(null, null, val)
      },
      

      async getList(page?: any, total?: any, limit?: any,data?:any) {
        if (page) {
          dataMap.listQuery.currentPage = page
        }
        if (limit) {
          dataMap.listQuery.pageCount = 10
        }
        console.log(total)
        dataMap.listLoading = true

        if (data){
        	dataMap.list = data.data
        	dataMap.total = data.total
        }
        else{
          const data:any = await getArticles(dataMap.listQuery,ArticleType.SSYS)
          //const data=zhihuiJigouJson        
          dataMap.list = [];
            if(data)
            {
              allData = data.data;
              dataMap.list = allData.slice((dataMap.listQuery.currentPage-1)*dataMap.listQuery.pageCount,(dataMap.listQuery.currentPage)*dataMap.listQuery.pageCount);
            }
            dataMap.total = data?.total ?? 0;
        }

        // Just to simulate the time of the request
        setTimeout(() => {
          dataMap.listLoading = false
        }, 0.5 * 1000)
      },
      handleFilter() {
        dataMap.listQuery.currentPage = 1
        dataMap.getList()
      },
      handleModifyStatus(row: any, status: string) {
      /*
        ElMessage.success({
          message: '操作成功',
          type: 'success'
        })
        row.status = status*/
       let jumpData = { type: "经济目标",name:row.title,lng:row.sourceURL,lat:row.imageURL};
        router.push({
					path: '/menu/menu1/menu12/menu127',
					query: jumpData,
				})
      },
      sortChange(data: any) {
        const { prop, order } = data
        if (prop === 'id') {
          dataMap.sortByID(order)
        }
      },
      sortByID(order: string) {
        if (order === 'ascending') {
          dataMap.listQuery.sort = '+id'
        } else {
          dataMap.listQuery.sort = '-id'
        }
        dataMap.handleFilter()
      },
      getSortClass(key: string) {
        const sort = dataMap.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      },
      resetTempArticleModel() {
        dataMap.tempArticleModel = cloneDeep(defaultArticleModel)
      },
      handleCreate() {
        router.push({
					path: '/menu/menu1/menu12/menu127',
					query: { type: "经济目标",name:''},	});
      },
      createData() {

      },

      handleUpdate(row: any) {
          dataMap.dialogStatus = 'update';
        dataMap.dialogFormVisible = true;
        (dialogPop.value as any).handleUpdate(row);
      },
      async updateData(tempArticleModel) {
            //tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            const res:any = await updateArticle(tempArticleModel,ArticleType.SSYS);
            if(res)
            {
              Assert.isFalse(true,res+"");
              return;
            }
            ElMessage.success('更新成功')
		        dataMap.dialogFormVisible = false;
		        const data:any = await getArticles(dataMap.listQuery,ArticleType.SSYS)		                
		       dataMap.list = [];
              if(data)
              {
                allData = data.data;
                dataMap.list = allData.slice((dataMap.listQuery.currentPage-1)*dataMap.listQuery.pageCount,(dataMap.listQuery.currentPage)*dataMap.listQuery.pageCount);
              }
              dataMap.total = data?.total ?? 0;
      },
      async handleDelete(row: any, index: number) {
      	await deleteArticle(row.id,ArticleType.SSYS).then(()=>{
        ElMessage.success({
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        dataMap.list.splice(index, 1)
        }).catch(err => {
	      ElMessage.warning('删除失败')
	     });
      },
      async handleGetPageviews(pageviews: string) {
        const data = await getPageviews({ pageviews })
        //const data = zhihuiJigouJson.data;
        dataMap.pageviewsData = data?.data.pageviews
        console.log(dataMap.pageviewsData)
        dataMap.dialogPageviewsVisible = true
      },
      handleDownload() {
        dataMap.downloadLoading = true
       
       const tHeader = ['编号', '时间', '名称', '类型', '重要性',"价值/规模","状态"]
        const filterVal = [
          'abstractContent',
          'timestamp',
          'title',
          'author',
          'status',
          'pageviews',
          'fullContent'
        ];
        let data = formatJson(filterVal, dataMap.list,false);
        exportJson2Excel(tHeader, data, "经济目标", undefined, undefined, true, "xlsx");
        dataMap.downloadLoading = false;
      },
      typeFilter: (type: string) => {
        return calendarTypeKeyValue[type]
      }
    })
    onMounted(() => {
      console.log(typeof ElForm)
      dataMap.getList(null, null, 10)
    })
    return { t,...toRefs(dataMap), dataForm,dialogPop}
  }
})
</script>
